package com.bestom.sharingbookcase.services;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.Network;
import android.net.NetworkCapabilities;
import android.net.NetworkRequest;
import android.net.NetworkSpecifier;
import android.net.wifi.WifiNetworkSpecifier;
import android.os.Binder;
import android.os.Build;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.IBinder;
import android.os.Looper;
import android.os.Message;
import android.os.PatternMatcher;
import android.text.TextUtils;
import android.util.Log;

import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;

import com.bestom.sharingbookcase.SharingBookcaseApp;

public class WifiService extends Service {
    private static final String TAG = "WifiService";
    private static final boolean DEBUG = true;

    private String ssid = "";
    private String pwd = "";

    private Context mContext;

    private static void LOG(String msg) {
        if (DEBUG) {
            Log.d(TAG, msg);
        }
    }

    private static volatile boolean mWorkHandleLocked = false;
    public static final int COMMAND_CHECK_REMOTE_UPDATING = 1;

    private WorkHandler mWorkHandler;

    private static final int connMaxCount = 50;
    private int currentConnCount = 0;

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return mBinder;
    }

    private final LocalBinder mBinder = new LocalBinder();

    public class LocalBinder extends Binder {

        public void unLockWorkHandler() {
            LOG("unLockWorkHandler...");
            mWorkHandleLocked = false;
        }

        public void LockWorkHandler() {
            mWorkHandleLocked = true;
            LOG("LockWorkHandler...!");
        }

    }

    @Override
    public void onCreate() {
        super.onCreate();
        mContext = this;

        HandlerThread workThread = new HandlerThread("WifiService : work thread");
        workThread.start();
        mWorkHandler = new WorkHandler(workThread.getLooper());
    }
    @RequiresApi(api = Build.VERSION_CODES.Q)
    private void connectAP_Q(String ssid, String pass) throws InterruptedException {

        ConnectivityManager connectivityManager = (ConnectivityManager)
                mContext.getSystemService(Context.CONNECTIVITY_SERVICE);

        NetworkSpecifier specifier = new WifiNetworkSpecifier.Builder()
                .setSsidPattern(new PatternMatcher(ssid, PatternMatcher.PATTERN_PREFIX))
                .setWpa2Passphrase(pass)
                .build();
        //创建一个请求
        NetworkRequest request = new NetworkRequest.Builder()
                .addTransportType(NetworkCapabilities.TRANSPORT_WIFI)//创建的是WIFI网络。
                .addCapability(NetworkCapabilities.NET_CAPABILITY_NOT_RESTRICTED)//网络不受限
                .addCapability(NetworkCapabilities.NET_CAPABILITY_TRUSTED)//信任网络，增加这个连个参数让设备连接wifi之后还联网。
                .setNetworkSpecifier(specifier)
                .build();
        connectivityManager.requestNetwork(request, new ConnectivityManager.NetworkCallback() {
            @Override
            public void onAvailable(Network network) {
                //TODO 连接OK，做些啥
                LOG("onAvailable.......");
            }

            @Override
            public void onUnavailable() {
                //TODO 连接失败，或者被用户取消了，做些啥
                LOG("onUnavailable.......");
            }
        });
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        connWifi = false;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        LOG("onStartCommand.......");

        if (intent == null) {
            return Service.START_NOT_STICKY;
        }

        Message msg = new Message();
        msg.what = COMMAND_CHECK_REMOTE_UPDATING;
        mWorkHandler.sendMessageDelayed(msg, 1000);

        return Service.START_REDELIVER_INTENT;
    }

    private class WorkHandler extends Handler {

        public WorkHandler(Looper looper) {
            super(looper);
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);

            if (msg.what == COMMAND_CHECK_REMOTE_UPDATING) {
                if (mWorkHandleLocked) {
                    LOG("WorkHandler::handleMessage() : locked !!!");
                    return;
                }
                connWifi = false;
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                String[] wifiInfo = WifiConfig.getWifiInfo(mContext);
                LOG("WifiConfig,ssid:" + wifiInfo[0] + ",pwd:" + wifiInfo[1]);
                ssid = wifiInfo[0];
                pwd = wifiInfo[1];

                if (!TextUtils.isEmpty(ssid) && !WIFIConnectionManager.getInstance(mContext).isConnected(ssid)) {
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
                        try {
                            connectAP_Q(ssid,pwd);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    //autoConnWifi();
                }
            }
        }
    }

    private boolean connWifi = false;

    private void autoConnWifi() {

        currentConnCount = 0;
        connWifi = true;
        new WIFIConnThread().start();
    }

    private class WIFIConnThread extends Thread {
        @Override
        public void run() {
            super.run();
            boolean connected = WIFIConnectionManager.getInstance(mContext).isConnected(ssid);
            LOG("connected = " + connected + ", currentConnCount= " + currentConnCount + ",ssid: " + ssid + ",pwd: " + pwd);
            while (connWifi && !connected && currentConnCount < connMaxCount) {

                currentConnCount++;
                connected = WIFIConnectionManager.getInstance(mContext).connect(ssid, pwd);
                LOG("mWorkHandler: wifi connected = " + connected + ", currentConnCount= " + currentConnCount + ",ssid: " + ssid + ",pwd: " + pwd);
                if (!connected){
                    try {
                        Thread.sleep(5000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
            if (connected) {
                LOG("- 网络连接成功");
                SharingBookcaseApp.getApplication().IGetMessageCallBack.setSuccess("ssid:" + ssid + "  pwdpwd:" + pwd);
            }
        }
    }
}
